﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using DTcms.Core.API.Filters;
using DTcms.Core.Common.Emum;
using DTcms.Core.Common.Extensions;
using DTcms.Core.Common.Helper;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using DTcms.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;

namespace DTcms.Core.API.Controllers
{
    /// <summary>
    /// 文章类别
    /// </summary>
    [Area("api")]
    [Route("api/article/category")]
    [ApiController]
    public class ArticleCategoryController : ControllerBase
    {
        private readonly IArticleCategoryService _articleCategoryService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;
        private readonly ISiteService _siteService;
        private readonly ISiteChannelService _siteChannelService;
        public ArticleCategoryController(IArticleCategoryService articleCategoryService,
            IUserService userService,
            ISiteService siteService,
            ISiteChannelService siteChannelService,
            IMapper mapper)
        {
            _articleCategoryService = articleCategoryService;
            _userService = userService;
            _mapper = mapper;
            _siteService = siteService;
            _siteChannelService = siteChannelService;
        }

        /// <summary>
        /// 根据ID获取数据
        /// 示例：/api/article/category/1/1
        /// </summary>
        [HttpGet("{channelId}/{id}")]
        [Authorize]
        [AuthorizeFilter("ArticleCategory", ActionType.View, "channelId")]
        public async Task<IActionResult> GetById([FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<ArticleCategoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //查询数据库获取实体
            var model = await _articleCategoryService.QueryAsync<ArticleCategory>(x => x.Id == id);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel
            //根据字段进行塑形
            var result = _mapper.Map<ArticleCategoryDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取指定数量列表
        /// 示例：/api/article/category/view/1/1/0
        /// </summary>
        [HttpGet("view/{channelId}/{parentId}/{top}")]
        [Authorize]
        [AuthorizeFilter("ArticleCategory", ActionType.View, "channelId")]
        public async Task<IActionResult> GetList([FromRoute] long parentId, [FromRoute] int top, [FromQuery] BaseParameter searchParam)
        {
            //检测参数是否合法
            if (!searchParam.Fields.IsPropertyExists<ArticleCategoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取数据库列表
            var resultFrom = await _articleCategoryService.QueryListAsync(top, parentId);
            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<ArticleCategoryDto>>(resultFrom).ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取树目录列表
        /// 示例：/api/article/category/1/1
        /// </summary>
        [HttpGet("{channelId}")]
        [Authorize]
        [AuthorizeFilter("ArticleCategory", ActionType.View, "channelId")]
        public async Task<IActionResult> GetList([FromQuery] BaseParameter param, [FromRoute] int channelId)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<ArticleCategoryDto>() || channelId <= 0)
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取数据库列表
            var resultFrom = await _articleCategoryService.QueryListAsync(channelId, 0);
            //使用AutoMapper转换成ViewModel
            //根据字段进行塑形
            var resultDto = resultFrom.ShapeData(param.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 添加一条记录
        /// 示例：/api/article/category/1
        /// </summary>
        [HttpPost("{channelId}")]
        [Authorize]
        [AuthorizeFilter("ArticleCategory", ActionType.Add, "channelId")]
        public async Task<IActionResult> Add([FromBody] ArticleCategoryAddDto modelDto)
        {
            //验证数据是否合法
            if (!TryValidateModel(modelDto))
            {
                return ValidationProblem(ModelState);
            }
            //获取当前用户名
            modelDto.AddBy = await _userService.GetUserNameAsync();
            modelDto.AddTime = DateTime.Now;
            //映射成实体
            var dtoModel = _mapper.Map<ArticleCategory>(modelDto);
            //检查频道是否存在
            if (!await _siteChannelService.ExistsAsync<SiteChannel>(x => x.Id == dtoModel.ChannelId))
            {
                return NotFound(ResponseMessage.Error($"频道{dtoModel.ChannelId}不存在或已删除"));
            }
            var channelModel = await _siteChannelService.QueryAsync(t => t.Id.Equals(dtoModel.ChannelId));
            //添加站点主键
            dtoModel.SiteId = channelModel.SiteId;
            //检查站点是否存在
            if (!await _siteService.ExistsAsync<Sites>(x => x.Id == dtoModel.SiteId))
            {
                return NotFound(ResponseMessage.Error($"站点{dtoModel.SiteId}不存在或已删除"));
            }

            //写入数据库
            var mapModel = await _articleCategoryService.AddAsync(dtoModel);
            //映射成DTO再返回，否则出错
            var result = _mapper.Map<ArticleCategoryDto>(mapModel);
            return Ok(result);
        }

        /// <summary>
        /// 修改一条记录
        /// 示例：/api/article/category/1/1
        /// </summary>
        [HttpPut("{channelId}/{id}")]
        [Authorize]
        [AuthorizeFilter("ArticleCategory", ActionType.Edit, "channelId")]
        public async Task<IActionResult> Update([FromRoute] long id, [FromBody] ArticleCategoryEditDto modelDto)
        {
            //验证数据是否合法
            if (!TryValidateModel(modelDto))
            {
                return ValidationProblem(ModelState);
            }
            var result = await _articleCategoryService.UpdateAsync(id, modelDto);
            return NoContent();
        }

        /// <summary>
        /// 局部更新一条记录
        /// 示例：/api/article/category/1/1
        /// Body：[{"op":"replace","path":"/title","value":"new title"}]
        /// </summary>
        [HttpPatch("{channelId}/{id}")]
        [Authorize]
        [AuthorizeFilter("ArticleCategory", ActionType.Edit, "channelId")]
        public async Task<IActionResult> Update([FromRoute] long id, [FromBody] JsonPatchDocument<ArticleCategoryEditDto> patchDocument)
        {
            //注意：要使用写的数据库进行查询，才能正确写入数据主库
            var model = await _articleCategoryService.QueryAsync<ArticleCategory>(x => x.Id == id, WriteRoRead.Write);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            var modelToPatch = _mapper.Map<ArticleCategoryEditDto>(model);
            patchDocument.ApplyTo(modelToPatch, ModelState);
            //验证数据是否合法
            if (!TryValidateModel(modelToPatch))
            {
                return ValidationProblem(ModelState);
            }
            //更新操作AutoMapper替我们完成，只需要调用保存即可
            _mapper.Map(modelToPatch, model);
            await _articleCategoryService.SaveAsync();

            return NoContent();
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/api/article/category/1/1
        /// </summary>
        [HttpDelete("{channelId}/{id}")]
        [Authorize]
        [AuthorizeFilter("ArticleCategory", ActionType.Delete, "channelId")]
        public async Task<IActionResult> Delete([FromRoute] long id)
        {
            if (!await _articleCategoryService.ExistsAsync<ArticleCategory>(x => x.Id == id))
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            var result = await _articleCategoryService.DeleteAsync(x => x.Id == id);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// 示例：/api/article/category/1?ids=1,2,3
        /// </summary>
        [HttpDelete("{channelId}")]
        [Authorize]
        [AuthorizeFilter("ArticleCategory", ActionType.Delete, "channelId")]
        public async Task<IActionResult> DeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _articleCategoryService.DeleteAsync(x => arrIds.Contains(x.Id));

            return NoContent();
        }

        #region 前台调用接口============================
        /// <summary>
        /// 根据ID获取数据
        /// 示例：/api/client/article/category/1
        /// </summary>
        [HttpGet("/api/client/article/category/{id}")]
        public async Task<IActionResult> ClientGetById([FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<ArticleCategoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //查询数据库获取实体
            var model = await _articleCategoryService.QueryAsync<ArticleCategory>(x => x.Id == id);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel
            //根据字段进行塑形
            var result = _mapper.Map<ArticleCategoryDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取指定数量列表
        /// 示例：/api/client/article/category/view/1/1/0
        /// </summary>
        [HttpGet("/api/client/article/category/view/{channelId}/{parentId}/{top}")]
        public async Task<IActionResult> ClientGetList([FromRoute] int channelId, [FromRoute] long parentId, [FromRoute] int top, [FromQuery] BaseParameter searchParam)
        {
            //检测参数是否合法
            if (!searchParam.Fields.IsPropertyExists<ArticleCategoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取数据库列表
            var resultFrom = await _articleCategoryService.QueryListAsync(channelId, top, parentId);
            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<ArticleCategoryDto>>(resultFrom).ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 根据频道ID或名称获取树目录列表
        /// 示例：/api/client/article/news/category
        ///       /api/client/article/1/category
        /// </summary>
        [HttpGet("/api/client/article/{channelKey}/category")]
        public async Task<IActionResult> ClientGetList([FromRoute] string channelKey, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<ArticleCategoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //检查是否频道ID或者名称
            SiteChannel channelModel = null;
            if (int.TryParse(channelKey, out int channelId))
            {
                channelModel = await _siteChannelService.QueryAsync(t => t.Id.Equals(channelId) && t.SiteId.Equals(param.SiteId));
            }
            if (channelModel == null)
            {
                channelModel = await _siteChannelService.QueryAsync(t => t.Name.Equals(channelKey) && t.SiteId.Equals(param.SiteId));
            }
            if (channelModel == null)
            {
                return BadRequest(ResponseMessage.Error("频道不存在"));
            }
            //如果有查询关健字
            long parentId = 0; //父节点ID
            if (param.Keyword.IsNotNullOrWhiteSpace())
            {
                var model = await _articleCategoryService.QueryAsync<ArticleCategory>(x => x.Title.Contains(param.Keyword));
                if (model == null)
                {
                    return NotFound(ResponseMessage.Error("暂无查询记录"));
                }
                parentId = model.Id;
            }
            //获取数据库列表
            var resultFrom = await _articleCategoryService.QueryListAsync(channelModel.Id, parentId);
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var resultDto = resultFrom.ShapeData(param.Fields);
            //返回成功200
            return Ok(resultDto);
        }
        #endregion
    }
}
